﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace ComToolkit.Data
{
    public class CommandHelper
    {
        internal static string[] SplitCommands(string text)
        {
            TextReader reader = new StringReader(text);
            List<string> querys = new List<string>();
            StringBuilder candidate = new StringBuilder();

            bool write = true;
            string term = "";
            while(reader.Peek() > -1)
            {
                char c = (char)reader.Read();
                if((c == '/' || c == '-')  && write)
                {
                    char next = (char)reader.Peek();
                    if(next == c)
                    {
                        write = false;
                        term = System.Environment.NewLine;
                    }else if(c == '/' && next == '*')
                    {
                        write = false;
                        term = "*/";
                    }
                }
                if(!write)
                {
                    if((term.Length == 1 && c == term[0])
                        || (term == new string(new[] { c, (char)reader.Peek()}))
                        )
                    {
                        if (term.Length == 2)
                            reader.Read();
                        write = true;
                    }
                }else
                {
                    if (c == ';' || (c == 'G' && (char)reader.Peek() == 'O' && char.IsWhiteSpace(candidate[candidate.Length - 1])))
                    {
                        querys.Add(candidate.ToString());
                        candidate.Clear();
                    }
                    else if(!char.IsWhiteSpace(c) || candidate.Length > 0)
                    {
                        candidate.Append(c);
                    }
                }
            }
            if(candidate.Length > 0)
                querys.Add(candidate.ToString());
            return querys.ToArray();
        }
    }
}
